package org.dromara.bykt.service.impl;

import org.dromara.bykt.domain.BYKTCourse;
import org.dromara.bykt.domain.BYKTCourseCategory;
import org.dromara.bykt.domain.BYKTCourseExercise;
import org.dromara.bykt.domain.vo.BYKTCourseCategoryVo;
import org.dromara.bykt.domain.vo.BYKTCourseVo;
import org.dromara.bykt.mapper.BYKTCourseCategoryMapper;
import org.dromara.bykt.mapper.BYKTCourseMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.bykt.domain.bo.BYKTCourseSimulationBo;
import org.dromara.bykt.domain.vo.BYKTCourseSimulationVo;
import org.dromara.bykt.domain.BYKTCourseSimulation;
import org.dromara.bykt.mapper.BYKTCourseSimulationMapper;
import org.dromara.bykt.service.IBYKTCourseSimulationService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 模拟卷Service业务层处理
 *
 * @author Hou
 * @date 2025-06-22
 */
@RequiredArgsConstructor
@Service
public class BYKTCourseSimulationServiceImpl implements IBYKTCourseSimulationService {

    private final BYKTCourseSimulationMapper baseMapper;

    private final BYKTCourseMapper courseMapper;

    private final BYKTCourseCategoryMapper courseCategoryMapper;

    /**
     * 查询模拟卷
     *
     * @param id 主键
     * @return 模拟卷
     */
    @Override
    public BYKTCourseSimulationVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询模拟卷列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 模拟卷分页列表
     */
    @Override
    public TableDataInfo<BYKTCourseSimulationVo> queryPageList(BYKTCourseSimulationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BYKTCourseSimulation> lqw = buildQueryWrapper(bo);
        Page<BYKTCourseSimulationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(this::processRelationData);
        return TableDataInfo.build(result);
    }

    private void processRelationData(BYKTCourseSimulationVo vo) {
        Long courseId = vo.getCourseId();
        BYKTCourseVo byktCourseVo = courseMapper.selectVoOne(new LambdaQueryWrapper<BYKTCourse>().eq(BYKTCourse::getId, courseId));
        if (byktCourseVo != null) {
            vo.setCourseName(byktCourseVo.getTitle());
            vo.setCategoryId(byktCourseVo.getCategoryId());
            BYKTCourseCategoryVo byktCourseCategoryVo = courseCategoryMapper.selectVoOne(new LambdaQueryWrapper<BYKTCourseCategory>().eq(BYKTCourseCategory::getId, byktCourseVo.getCategoryId()));
            if (byktCourseCategoryVo != null) {
                vo.setCategoryName(byktCourseCategoryVo.getName());
            }
        }
    }

    /**
     * 查询符合条件的模拟卷列表
     *
     * @param bo 查询条件
     * @return 模拟卷列表
     */
    @Override
    public List<BYKTCourseSimulationVo> queryList(BYKTCourseSimulationBo bo) {
        LambdaQueryWrapper<BYKTCourseSimulation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BYKTCourseSimulation> buildQueryWrapper(BYKTCourseSimulationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BYKTCourseSimulation> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BYKTCourseSimulation::getSort);
        if (bo.getCategoryId() != null) {
            List<BYKTCourse> courses = courseMapper.selectList(new LambdaQueryWrapper<BYKTCourse>().eq(BYKTCourse::getCategoryId, bo.getCategoryId()));
            // 提取所有 ID 到 List<Long>
            List<Long> courseIds = courses.stream()
                .map(BYKTCourse::getId)
                .collect(Collectors.toList());
            lqw.in(BYKTCourseSimulation::getCourseId, courseIds);
        }
        lqw.eq(bo.getVideoId() != null, BYKTCourseSimulation::getVideoId, bo.getVideoId());
        lqw.eq(bo.getCourseId() != null, BYKTCourseSimulation::getCourseId, bo.getCourseId());
        lqw.eq(bo.getSimulationId() != null, BYKTCourseSimulation::getSimulationId, bo.getSimulationId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BYKTCourseSimulation::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), BYKTCourseSimulation::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getOptions()), BYKTCourseSimulation::getOptions, bo.getOptions());
        lqw.eq(StringUtils.isNotBlank(bo.getAnswer()), BYKTCourseSimulation::getAnswer, bo.getAnswer());
        lqw.eq(StringUtils.isNotBlank(bo.getAnalysis()), BYKTCourseSimulation::getAnalysis, bo.getAnalysis());
        lqw.eq(StringUtils.isNotBlank(bo.getImage()), BYKTCourseSimulation::getImage, bo.getImage());
        lqw.eq(bo.getScore() != null, BYKTCourseSimulation::getScore, bo.getScore());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionType()), BYKTCourseSimulation::getQuestionType, bo.getQuestionType());
        return lqw;
    }

    /**
     * 新增模拟卷
     *
     * @param bo 模拟卷
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BYKTCourseSimulationBo bo) {
        bo.setCreateTime(new Date());
        BYKTCourseSimulation add = MapstructUtils.convert(bo, BYKTCourseSimulation.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模拟卷
     *
     * @param bo 模拟卷
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BYKTCourseSimulationBo bo) {
        bo.setUpdateTime(new Date());
        BYKTCourseSimulation update = MapstructUtils.convert(bo, BYKTCourseSimulation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BYKTCourseSimulation entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除模拟卷信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public BYKTCourseSimulationVo selectText(String title) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<>(BYKTCourseSimulation.class).eq(BYKTCourseSimulation::getTitle, title));
    }

    @Override
    public Long queryVideoId(Long videoId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseSimulation>().eq(BYKTCourseSimulation::getVideoId, videoId));
    }

    @Override
    public Long queryCourseId(Long courseId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseSimulation>().eq(BYKTCourseSimulation::getCourseId, courseId));
    }
}
